//
//  EFAPjtDeviceListVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/14.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtDeviceListVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtDetailTCell.h"
#import "EFAPjtDevEditTCell.h"
#import "EFAModel.h"
#import "GlobalHeader.h"
#import "EFAPjtDeviceAddVC.h"
#import "EFAPjtDevResultsTVC.h"
#import "UIColor+XDHex.h"
#import "UIImage+XDAdd.h"

@interface EFAPjtDeviceListVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAPjtDevEditTCellDelegate, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *addBarBtnItem;
@property (strong, nonatomic) UISearchController *searchController;
//@property (nonatomic, strong) EFADeviceModel *deviceModel;
@end

static NSString *const kReuseCellId = @"EFAPjtDetailTCell";
static NSString *const kReuseEditCellId = @"EFAPjtDevEditTCell";
static NSInteger const kRequestSize = 20;

@implementation EFAPjtDeviceListVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

//- (BOOL)hidesBottomBarWhenPushed {
//    return self.viewType == EFAPjtManagerVCTypeManager;
//}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备列表";
    self.navigationItem.rightBarButtonItem = self.addBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    self.definesPresentationContext = YES;  ///< 这里会影响到搜索结果页面的下拉刷新那里的偏移量
    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = self.searchController;
    } else {
        [self.headerBgView addSubview:self.searchController.searchBar];
        self.tableView.tableHeaderView = self.headerBgView;
        //    self.tableView.tableHeaderView = self.searchController.searchBar; ///< 直接设置为headerview，体验最好，但是mjrefresh会受到影响，蛋疼
    }
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    UINib *editNib = [UINib nibWithNibName:kReuseEditCellId bundle:nil];
    [self.tableView registerNib:editNib forCellReuseIdentifier:kReuseEditCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
//    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有设备" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.pjtDetail.device_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger curUserId = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id;
    return (curUserId == self.pjtDetail.project_info.efairyproject_creator_id) ? 2 : 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        EFAPjtDetailTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        if (indexPath.section < self.pjtDetail.device_list.count) {
            [cell configViewWithDeviceListItem:self.pjtDetail.device_list[indexPath.section]];
        }
        return cell;
    } else {
        EFAPjtDevEditTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseEditCellId forIndexPath:indexPath];
        cell.delegate = self;
        return cell;
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0 && indexPath.section < self.pjtDetail.device_list.count) {
        EFADeviceListItem *item = self.pjtDetail.device_list[indexPath.section];
        [self jumpToDeviceDetailWithDevItem:item];
    }
}
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"输入的搜索词语是%@", searchString);
    
    // hand over the filtered results to our search results table
    EFAPjtDevResultsTVC *tableController = (EFAPjtDevResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = searchString;
    tableController.project_id = self.pjtDetail.project_info.efairyproject_id;
    tableController.project_owner_id = self.pjtDetail.project_info.efairyproject_creator_id;
    [tableController refreshNewData];
}
#pragma mark - UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController {
//    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
    
    EFAPjtDevResultsTVC *tableController = (EFAPjtDevResultsTVC *)self.searchController.searchResultsController;
    tableController.needRefresh = NO;
}
- (void)didDismissSearchController:(UISearchController *)searchController {
//    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    
    EFAPjtDevResultsTVC *tableController = (EFAPjtDevResultsTVC *)self.searchController.searchResultsController;
    if (tableController.needRefresh) {
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - EFAPjtDevEditTCellDelegate
- (void)pjtDevEditTCell:(EFAPjtDevEditTCell *)cell editBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    EFADeviceListItem *item = self.pjtDetail.device_list[indexPath.section];
    
    EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeEdit];
    vc.project_id = self.pjtDetail.project_info.efairyproject_id;
    vc.deviceItem = item;
    vc.successHandle = ^{
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self showViewController:vc sender:nil];
}
- (void)pjtDevEditTCell:(EFAPjtDevEditTCell *)cell delBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"确定要删除该设备吗?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [vc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self requestDeleteDeviceWith:indexPath];
    }]];
    [self showDetailViewController:vc sender:nil];
}

#pragma mark - event response
- (void)addBarBtnTapped:(UIBarButtonItem *)item {
    EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeAdd];
    vc.project_id = self.pjtDetail.project_info.efairyproject_id;
    vc.successHandle = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self showViewController:vc sender:nil];
}
#pragma mark - private methods
- (void)jumpToDeviceDetailWithDevItem:(EFADeviceListItem *)item {
    EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeDetail];
    vc.project_id = self.pjtDetail.project_info.efairyproject_id;
    vc.deviceItem = item;
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.pjtDetail.isDeviceTotalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self.tableView.mj_footer setHidden:YES];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
        [self.tableView.mj_footer setHidden:NO];
    }
    self.tableView.mj_footer.hidden = self.pjtDetail.isDeviceTotalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestPjtDeviceListWithHeader:isHeader];
}

//- (EFADeviceModel *)deviceModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
//    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
//        return self.deviceModel;
//    }
//    
//    EFADeviceModel *temp = [EFADeviceModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
//    if (!temp) {
//        return self.deviceModel;
//    }
//    
//    if (AddMore && self.deviceModel) {
//        [self.deviceModel addMoreWithData:temp];
//    } else {
//        self.deviceModel = temp;
//    }
//    return self.deviceModel;
//}

#pragma mark - network request
- (void)requestPjtDeviceListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.pjtDetail.device_list.lastObject.efairydevice_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyproject_id" : @(self.pjtDetail.project_info.efairyproject_id),
//                           @"keyword" : @"",
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiPjtMgrDevList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
//        [self deviceModelWithDictionary:responseObject isAddMore:!isHeader];
        [self.pjtDetail deviceListWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestDeleteDeviceWith:(NSIndexPath *)indexPath {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    if (indexPath.section >= self.pjtDetail.device_list.count) {
        return;
    }
    EFADeviceListItem *item = self.pjtDetail.device_list[indexPath.section];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyproject_id" : @(self.pjtDetail.project_info.efairyproject_id),
                           @"efairydevice_id_list" : [@[@(item.efairydevice_id)] yy_modelToJSONString]};
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiPjtMgrDevice] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求删除设备返回：%@", responseObject);
        [hud hideAnimated:YES];
        [self.pjtDetail.device_list removeObjectAtIndex:indexPath.section];
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求删除设备失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)addBarBtnItem {
    if (!_addBarBtnItem) {
        _addBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(addBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_addBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _addBarBtnItem;
}
- (UISearchController *)searchController {
    if (!_searchController) {
        EFAPjtDevResultsTVC *tvc = [[EFAPjtDevResultsTVC alloc] init];
        _searchController = [[UISearchController alloc] initWithSearchResultsController:tvc];
        _searchController.searchResultsUpdater = self; ///< 设置UISearchControllerDelegate协议代理
        _searchController.dimsBackgroundDuringPresentation = YES;///<是否添加半透明覆盖层
        _searchController.hidesNavigationBarDuringPresentation = YES;///< 是否隐藏导航栏
        _searchController.delegate = self;
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.placeholder = @"输入设备昵称或UUID";
        
        if (@available(iOS 11.0, *)) {
            ;
        } else {
            UIImage* searchBarBg = [UIImage xd_getImageWithColor:[UIColor whiteColor] andHeight:1.0f];
            [_searchController.searchBar setBackgroundImage:searchBarBg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            _searchController.searchBar.barTintColor = [UIColor whiteColor];
            UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
            if (searchField) {
                [searchField setBackgroundColor:[UIColor xd_colorWithHex:0xEEEEEE]];
                searchField.layer.cornerRadius = 4.0f;
                searchField.layer.masksToBounds = YES;
            }
        }
        
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    }
    return _searchController;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
